package com.oanda.blackberry.ui;

import java.util.Timer;
import java.util.TimerTask;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.GIFEncodedImage;
import net.rim.device.api.system.Memory;
import net.rim.device.api.system.MemoryStats;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.NullField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;

import com.oanda.blackberry.util.DefaultController;

public class OandaMainScreen extends TransitionMainScreen {
    HorizontalFieldManager hStatus = new HorizontalFieldManager();
    LabelField statusLabel = new LabelField() {
        public void paint(Graphics g) {
            g.setColor(16119285);
            super.paint(g);
        }
    };

    String statusText = "";

    HorizontalFieldManager titleManager = new HorizontalFieldManager(1152921504606846976L);
    ColoredEditField titleField = new ColoredEditField(14540253, "", "", 45035996273704960L);

    private boolean showThrobber = false;
    private boolean showThrobberOandaHeader = false;

    Bitmap header = Bitmap.getBitmapResource("header-480x97.png");

    public static int BG_COLOR = 4473924;

    Timer textBlendingTimer = new Timer();
    TimerTask textBlendingTimerTask = new AlphaBlendingAnimationTimerTask(null);

    Timer timer = new Timer();
    TimerTask task;
    GIFFUtility throbberRenderer;
    int w = Display.getWidth();
    int h = Display.getHeight();

    boolean isErrorDisplayed = false;

    boolean showGraphicStatus = false;

    private int ALPHA_MAX = 240;
    private int ALPHA = 0;

    boolean titleManagerCreated = false;

    public OandaMainScreen() {
        getMainManager().setBackground(BackgroundFactory.createSolidBackground(4473924));
        createTitledManager();

        this.hStatus.add(this.statusLabel);
        this.hStatus.setBackground(BackgroundFactory.createSolidTransparentBackground(0, 150));

        this.statusLabel.setFont(DefaultController.getComponentFont().derive(0, 14));

        this.timer = new Timer();
        EncodedImage thImage = EncodedImage.getEncodedImageResource("ajax-loader3.bin");
        this.throbberRenderer = new GIFFUtility((GIFEncodedImage) thImage);
    }

    public void setStatusField(final String message) {
        if (!this.isErrorDisplayed)
            UiApplication.getUiApplication().invokeLater(new Runnable() {

                public void run() {
                    OandaMainScreen.this.statusText = message;
                    OandaMainScreen.this.showGraphicStatus = true;
                    OandaMainScreen.this.invalidate();
                    OandaMainScreen.this.startTextBlending();
                }
            });
    }

    public void diplayError(final String message, final int interval) {
        if (!this.isErrorDisplayed)
            UiApplication.getUiApplication().invokeLater(new Runnable() {

                public void run() {
                    OandaMainScreen.this.ALPHA = OandaMainScreen.this.ALPHA_MAX;
                    OandaMainScreen.this.statusText = message;
                    OandaMainScreen.this.isErrorDisplayed = true;
                    OandaMainScreen.this.showGraphicStatus = true;

                    new Timer().schedule(new TimerTask() {
                        public void run() {
                            OandaMainScreen.this.isErrorDisplayed = false;
                            OandaMainScreen.this.removeStatusField();
                        }
                    }, interval);

                    OandaMainScreen.this.invalidate();
                }
            });
    }

    public void diplayError(final String message, final int interval, final String newMessage) {
        if (!this.isErrorDisplayed)
            UiApplication.getUiApplication().invokeLater(new Runnable() {

                public void run() {
                    OandaMainScreen.this.ALPHA = OandaMainScreen.this.ALPHA_MAX;
                    OandaMainScreen.this.statusText = message;
                    OandaMainScreen.this.isErrorDisplayed = true;
                    OandaMainScreen.this.showGraphicStatus = true;

                    new Timer().schedule(new TimerTask() {
                        public void run() {
                            OandaMainScreen.this.isErrorDisplayed = false;
                            OandaMainScreen.this.removeStatusField();
                            OandaMainScreen.this.setStatusField(OandaMainScreen.this.statusText);
                        }
                    }, interval);

                    OandaMainScreen.this.invalidate();
                }
            });
    }

    public void removeStatusField() {
        if (!this.isErrorDisplayed)
            UiApplication.getUiApplication().invokeLater(new Runnable() {
                public void run() {
                    OandaMainScreen.this.ALPHA = OandaMainScreen.this.ALPHA_MAX;
                    OandaMainScreen.this.showGraphicStatus = false;
                    OandaMainScreen.this.setStatus(new NullField());
                    OandaMainScreen.this.invalidate();
                }
            });
    }

    private void startTextBlending() {
        this.ALPHA = 0;
        stopTextBlending();
        if (this.textBlendingTimerTask == null)
            this.textBlendingTimerTask = new AlphaBlendingAnimationTimerTask(null);
        if (this.textBlendingTimer == null) {
            this.textBlendingTimer = new Timer();
        }
        this.textBlendingTimer.schedule(this.textBlendingTimerTask, 100L);
    }

    private void stopTextBlending() {
        if (this.textBlendingTimerTask != null)
            this.textBlendingTimerTask.cancel();
        if (this.textBlendingTimer != null) {
            this.textBlendingTimer.cancel();
        }
        this.textBlendingTimer = null;
        this.textBlendingTimerTask = null;
    }

    public void paint(Graphics g) {
        super.paint(g);

        if ((this.HorizontalOffset == 0) || (this.showThrobber)) {
            if (this.showThrobberOandaHeader) {
                g.drawBitmap(0, 0, this.header.getWidth(), this.header.getHeight(), this.header, 0,
                        0);
            }
            g.setGlobalAlpha(245);
            g.setColor(BG_COLOR);

            if (this.showThrobberOandaHeader)
                g.fillRect(0, this.header.getHeight(), 480,
                        Display.getHeight() - this.header.getHeight());
            else {
                g.fillRect(0, this.titleManager.getHeight(), 480, Display.getHeight()
                        - this.titleManager.getHeight());
            }
            g.pushRegion((this.w - 32) / 2, (this.h - 32) / 2, 32, 32, 0, 0);
            this.throbberRenderer.paint(g);
            g.popContext();
        }
        if (this.showGraphicStatus) {
            g.setColor(0);
            Font f = DefaultController.getComponentFont();
            f = f.derive(0, 20);
            g.setFont(f);

            int textWidth = f.getAdvance(this.statusText);
            int textHeight = f.getAscent();

            if (textWidth < this.w) {
                g.setGlobalAlpha(this.ALPHA - 60);

                g.setColor(10066329);
                g.fillRoundRect(0, this.h - textHeight - 8 - 2, this.w, 1, 5, 5);
                g.setColor(0);
                g.fillRoundRect(0, this.h - textHeight - 8, this.w, textHeight + 8, 0, 0);

                g.setGlobalAlpha(this.ALPHA);
                g.setColor(16777215);
                g.drawText(this.statusText, (this.w - textWidth) / 2, this.h - 1, 0x28 | 0x4);
            } else {
                this.statusLabel.setText(this.statusText);
                setStatus(this.hStatus);
            }
        }
    }

    public void updateTitle(final String newTitle) {
        Runnable r = new Runnable() {
            public void run() {
                UiApplication.getUiApplication().getScreenCount();
                OandaMainScreen.this.titleField.setText(newTitle);
            }
        };
        UiApplication.getUiApplication().invokeLater(r);
    }

    private void createTitledManager() {
        if (!this.titleManagerCreated)
            try {
                this.titleField.setFont(DefaultController.getComponentFont().derive(0, 18));
                this.titleManager.add(this.titleField);
                setTitle(this.titleManager);
                this.titleManagerCreated = true;
            } catch (IllegalArgumentException i) {
            }
    }

    public void showThrobber() {
        if (!this.showThrobber) {
            this.showThrobber = true;
            this.showThrobberOandaHeader = true;
            if (this.task == null)
                this.task = new AnimationTimerTask(null);
            if (this.timer == null) {
                this.timer = new Timer();
            }
            this.timer.schedule(this.task, 200L, 100L);
            invalidate();
        }
    }

    public void showThrobberPlain() {
        if (!this.showThrobber) {
            this.showThrobber = true;
            this.showThrobberOandaHeader = false;
            if (this.task == null)
                this.task = new AnimationTimerTask(null);
            if (this.timer == null) {
                this.timer = new Timer();
            }
            this.timer.schedule(this.task, 200L, 100L);
            invalidate();
        }
    }

    public void hideThrobber() {
        if (this.showThrobber) {
            this.showThrobber = false;
            if (this.task != null)
                this.task.cancel();
            if (this.timer != null) {
                this.timer.cancel();
            }
            this.timer = null;
            this.task = null;
            invalidate();
        }
    }

    public boolean onClose() {
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
                OandaMainScreen.this.titleManager.deleteAll();
                OandaMainScreen.this.deleteAll();
            }
        });
        return super.onClose();
    }

    String getFreeRam() {
        MemoryStats memoryStats = Memory.getRAMStats();
        int i = memoryStats.getFree() / 1024;

        return String.valueOf(i);
    }

    String getAlocated() {
        MemoryStats memoryStats = Memory.getRAMStats();
        int i = memoryStats.getAllocated() / 1024;

        return String.valueOf(i);
    }

    public HorizontalFieldManager getTitleManager() {
        return this.titleManager;
    }

    private class AlphaBlendingAnimationTimerTask extends TimerTask {
        private final OandaMainScreen oandaMainScreen;

        public AlphaBlendingAnimationTimerTask(OandaMainScreen oandaMainScreen) {
            this.oandaMainScreen = oandaMainScreen;
        }

        public void run() {
            while (oandaMainScreen.ALPHA < oandaMainScreen.ALPHA_MAX) {
                oandaMainScreen.ALPHA = oandaMainScreen.ALPHA_MAX / 2;
                oandaMainScreen.invalidate(0, oandaMainScreen.h - 35, oandaMainScreen.w, 35);
                try {
                    Thread.sleep(130L);
                } catch (InterruptedException ex) {
                }
            }
            oandaMainScreen.ALPHA = oandaMainScreen.ALPHA_MAX;
            oandaMainScreen.invalidate(0, oandaMainScreen.h - 25, oandaMainScreen.w, 25);
        }

    }

    private class AnimationTimerTask extends TimerTask {
        private final OandaMainScreen oandaMainScreen;

        public void run() {
            oandaMainScreen.throbberRenderer.nextPosition();
            oandaMainScreen.invalidate((oandaMainScreen.w - 32) / 2, (oandaMainScreen.h - 32) / 2,
                    32, 32);
        }

        public AnimationTimerTask(OandaMainScreen oandaMainScreen) {
            this.oandaMainScreen = oandaMainScreen;
        }
    }
}
